//
//  HMOAuthViewController.swift
//  weibo
//
//  Created by LCH on 16/3/5.
//  Copyright © 2016年 lch. All rights reserved.
//

import UIKit
import SVProgressHUD

 let WB_appKey = "3643380519"
 let WB_REDIRECT_URI = "http://www.itheima.com"
 let WB_APPSECRET = "7af1ed6675d7e5f29ee8a91e1cf8eb4f"

class HMOAuthViewController: UIViewController {
    
    private lazy var OAuthLoginUrl = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(WB_appKey)&redirect_uri=\(WB_REDIRECT_URI)")!
    
    // https://api.weibo.com/oauth2/authorize?client_id=3643380519&redirect_uri=http://www.itheima.com
    override func loadView() {
        
        view = webView
        
        let request = NSURLRequest(URL:OAuthLoginUrl)
        
        webView.loadRequest(request)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

       setupUI()
       
        }

  private func setupUI() {
    
      navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: nil, title: "返回", target: self, action: "back")
    
      navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: nil, title: "自动填充", target: self, action:"autoFill" )
    
    navigationItem.title = "自定义微博"
    
    }
    
    @objc private func back() {
    
      dismissViewControllerAnimated(true, completion: nil)
    
    }
    
   
    @objc private func autoFill() {
    
    let jsString = "document.getElementById('userId').value='314730767@qq.com';document.getElementById('passwd').value='lch9027'"
        
        webView.stringByEvaluatingJavaScriptFromString(jsString)
        
        
    
    }
    
    private lazy var webView:UIWebView = {
    
     let webView = UIWebView()
    
     webView.delegate = self
        
    return webView
    
    }()

}


extension HMOAuthViewController: UIWebViewDelegate {

    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        print("webView加载的url:\(request.URL?.absoluteString)")
        
        guard let url = request.URL else {
        
          return true
        }
        // 为什么不能通过where或者'进行判断
        let urlStr = url.absoluteString
        if urlStr.hasPrefix(WB_REDIRECT_URI) {
        
         let query = url.query!
        
        let code = query.substringFromIndex("code=".endIndex)
//        let code2 = urlStr.substringFromIndex("http://www.itheima.com/?code=".endIndex)
        
         
         print(code)
            
        HMUserAccountViewModel.sharedAccountViewModel.loadAccessToken(code, callback: { (isSuccess) -> () in
            
            if isSuccess {
            
             print("HMOAuthViewController请求数据成功")
//             let delegate = UIApplication.sharedApplication().delegate as? AppDelegate
//               let window = delegate?.window
//                window?.rootViewController = HMWelcomeViewController()
            NSNotificationCenter.defaultCenter().postNotificationName("HMSwitchViewController", object: self)
                
            }else {
            
              SVProgressHUD.showErrorWithStatus("由于某些原因登录失败")
            }
            
        })
            
        
              return false
        
        }
       return true
        
    }
    
//    private func loadAccessToken(code:String) {
//    
//    let urlString = "https://api.weibo.com/oauth2/access_token"
//    
//        let parameters = [
//            "client_id": WB_appKey,
//            "client_secret": WB_APPSECRET,
//            "grant_type": "authorization_code",
//            "code": code,
//            "redirect_uri":WB_REDIRECT_URI
//        
//        ]
//    
//        HMNetworkTools.sharedTools.requst(.POST, urlString: urlString, parameters: parameters) { (responseObject, error) -> () in
//            
//            if error != nil {
//            
//            print("\(error)")
//            return
//                
//            }
//            print(responseObject)
//            let account = HMUserAccount(dict:responseObject!)
//            print(account)
//            
//            self.loadUserInfo(account)
//        }
//    
//    }
//    
//    private func loadUserInfo(account:HMUserAccount) {
//    
//        let urlString = "https://api.weibo.com/2/users/show.json"
//        
//        guard let accessToken = account.access_token, uid = account.uid else{
//        
//          print("参数不够")
//            
//          return
//        
//        }
//        let parameters = [
//        
//            "access_token" : accessToken,
//            "uid": uid
//        
//        ]
//        
//        HMNetworkTools.sharedTools.requst(.GET, urlString: urlString, parameters: parameters) { (responseObject, error) -> () in
//            
//            if error != nil {
//            
//              print("个人信息请求错误")
//             SVProgressHUD.showErrorWithStatus("个人信息请求错误")
//               return
//            
//            }
//            print(responseObject)
//            
//             account.screen_name = responseObject!["screen_name"] as? String
//             account.avatar_large = responseObject!["avatar_large"] as? String
//            
//            // 为什么这要用归档 偏好设置也可以
//            let file = (NSSearchPathForDirectoriesInDomains(.DocumentationDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.archive")
//            
//            print(file)
//            
//            NSKeyedArchiver.archiveRootObject(account, toFile: file)
//            
//        }
//    
//    
//    
//    }
   
}
